package com.hwatsang.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hwatsang.dao.SmsAuthCodeDao;
import com.hwatsang.model.SmsAuthCode;
import com.hwatsang.service.SmsAuthCodeService;
import com.hwatsang.service.SmsService;

public class SmsAuthCodeServiceImpl implements SmsAuthCodeService {
	
	private static final Logger logger = LoggerFactory.getLogger(SmsAuthCodeServiceImpl.class);
	
	private static final int EXPIRED_MINUTES = 15;
	private static final String AUTH_CODE_PLACEHOLDER = "$authCode";
	private static final String SMS_TEMPLATE = 
			"欢迎注册华藏网，您的短信验证码为【" + AUTH_CODE_PLACEHOLDER + "】，请于" + EXPIRED_MINUTES + "分钟内在认证页面输入此验证码并提交。";	
	
	@Autowired
	private SmsAuthCodeDao smsAuthCodeDao;
	@Autowired
	private SmsService smsService;
	
	public String generateAndSendAuthCodeForUser(String userId, String mobileNumber) {		
		String code = String.valueOf((int)(Math.random()*9000 + 1000));
		SmsAuthCode authCode = smsAuthCodeDao.getAuthCodeByUserId(Long.valueOf(userId));
		if(authCode == null) {
			authCode = new SmsAuthCode();
			authCode.setUserId(Long.valueOf(userId));
			authCode.setGmtCreate(new Date());
			authCode.setGmtExpired(DateUtils.addMinutes(authCode.getGmtCreate(), EXPIRED_MINUTES));			
			authCode.setAuthCode(code);
			smsAuthCodeDao.createSmsAuthCode(authCode);
		} else {
			authCode.setAuthCode(code);
			authCode.setGmtExpired(DateUtils.addMinutes(new Date(), EXPIRED_MINUTES));
			smsAuthCodeDao.updateSmsAuthCode(authCode);
		}		
		
		logger.info("SMS auth code {} generated for user {}.", code, userId);
		
		smsService.sendSms(mobileNumber, StringUtils.replace(SMS_TEMPLATE, AUTH_CODE_PLACEHOLDER, code));
		
		return code;
	}

	public String getAuthCodeByUser(String userId) {
		SmsAuthCode authCode = smsAuthCodeDao.getAuthCodeByUserId(Long.valueOf(userId));
		if(authCode != null) {
			Date expiredDate = authCode.getGmtExpired();
			if(new Date().compareTo(DateUtils.addMinutes(expiredDate, EXPIRED_MINUTES)) > 0) {				
				// sms auth code will expired after 15 minutes!
				smsAuthCodeDao.deleteSmsAuthCodeById(authCode.getId());
				return null;
			}
			return authCode.getAuthCode();
		} else {
			return null;
		}
	}

	public void deleteAuthCodeForUser(long userId) {
		smsAuthCodeDao.deleteSmsAuthCodeByUserId(userId);
	}

}
